package com.project.config.interceptor.validate;

import com.project.utils.result.ResultTools;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.List;

/**
 * @author : Mr.Yan
 * @program : com.project.config.interceptor.validate
 * @create : 2020/06/04
 * @description : 切面验证参数的校验
 */
@Slf4j
@Aspect
@Component
public class AutoValidateParam {

    /**
      * @author : Mr.Yan
      * @create : 2020/6/4
      * @description : 定义切入点
      */
    @Pointcut("@annotation(com.project.utils.annotation.AutoValid)")
    public void validatePoint() {
    }
    @Around("validatePoint()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        BindingResult bindingResult = null;
        for(Object arg:joinPoint.getArgs()){
            if(arg instanceof BindingResult){
                bindingResult = (BindingResult) arg;
            }
        }
        if(bindingResult != null){
            List<ObjectError> errors = bindingResult.getAllErrors();
            if(errors.size()>0){
                StringBuilder msg = new StringBuilder();
                for(ObjectError error :errors){
                    msg.append(error.getDefaultMessage());
                    msg.append(";");
                }
                return ResultTools.fail(msg.toString());
            }
        }
        return joinPoint.proceed();
    }

}
